using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web;
using Blazing.BusinessObjects.Cms;
using System.Web.UI.WebControls;

namespace Blazing.Web.Controls
{
    [NonVisualControl, Themeable(true)]
    public class StatisticsControl : UserControl
    {
        CmsManager _manager = null;
        public CmsManager Manager
        {
            get
            {
                if (_manager == null)
                    _manager = Blazing.Util.CmsManagerHelper.FindManagerObject(Page.Controls);
                if (_manager == null)
                    throw new ApplicationException("There was no active CmsManager object found on the current page.");
                return _manager;
            }
        }

        public bool Enabled
        {
            get
            {
                object obj = ViewState["Enabled"];
                if (obj != null)
                    return (bool)obj;
                return false;
            }
            set
            {
                ViewState["Enabled"] = value;
            }
        }

        private bool Logged
        {
            get
            {
                object obj = ViewState["Logged"];
                if (obj != null)
                    return (bool)obj;
                return false;
            }
            set
            {
                ViewState["Logged"] = value;
            }
        }

        StatisticVisitor _visitor;
        public StatisticVisitor Visitor
        {
            get
            {
                if (_visitor == null)
                {
                    Guid retval = Guid.Empty;
                    HttpCookie trackUser = Request.Cookies["UserTracking"];

                    if (trackUser == null)
                    {
                        trackUser = new HttpCookie("UserTracking");
                        retval = Guid.NewGuid();
                        trackUser.Value = retval.ToString();
                        trackUser.Expires = DateTime.Now.AddDays(30);
                        Response.Cookies.Add(trackUser);
                    }
                    else if (trackUser != null && string.IsNullOrEmpty(trackUser.Value))
                    {
                        retval = Guid.NewGuid();
                        trackUser.Value = retval.ToString();
                    }
                    else
                    {
                        retval = new Guid(trackUser.Value);
                    }

                    _visitor = CmsFacade.GetVisitorByGuid(retval);
                    if (_visitor == null)
                    {
                        _visitor = new StatisticVisitor();
                        _visitor.Guid = retval;
                        _visitor.Save();
                    }
                }
                return _visitor;
            }
        }

        StatisticUseragent _agent;
        public StatisticUseragent UserBrowser
        {
            get
            {
                if (_agent == null)
                {
                    _agent = CmsFacade.GetUserAgentByName(Request.UserAgent);
                    if (_agent == null)
                    {
                        _agent = new StatisticUseragent();
                        _agent.Name = Request.UserAgent;
                        _agent.Save();
                    }
                }
                return _agent;
            }
        }

        StatisticOperatingSystem _operatingsystem;
        public StatisticOperatingSystem VisitorOS
        {
            get
            {
                if (_operatingsystem == null)
                {
                    _operatingsystem = CmsFacade.GetOperatingSystemByName(Request.Browser.Platform);
                    if (_operatingsystem == null)
                    {
                        _operatingsystem = new StatisticOperatingSystem();
                        _operatingsystem.Name = Request.Browser.Platform;
                        _operatingsystem.Save();
                    }
                }
                return _operatingsystem;
            }
        }

        StatisticSession _session;
        public StatisticSession VisitorSession
        {
            get
            {
                
                Guid retval = Guid.Empty;
                HttpCookie trackUser = Request.Cookies["UserSessionTracking"];

                if (trackUser == null)
                {
                    trackUser = new HttpCookie("UserSessionTracking");
                    retval = Guid.NewGuid();
                    trackUser["id"] = retval.ToString();
                    Response.Cookies.Add(trackUser);
                }
                else if (trackUser != null && string.IsNullOrEmpty(trackUser.Value))
                {
                    retval = Guid.NewGuid();
                    trackUser["id"] = retval.ToString();
                }
                else
                {
                    retval = new Guid(trackUser["id"]);
                }

                if (_session == null)
                {
                    _session = CmsFacade.GetSessionByKey(retval.ToString());
                    if (_session == null)
                    {
                        _session = new StatisticSession();
                        _session.IpAddress = Request.UserHostAddress;
                        _session.OperatingSystem = VisitorOS;
                        _session.SessionKey = retval.ToString();
                        _session.Useragent = UserBrowser;
                        _session.Visitor = Visitor;
                        _session.Save();
                    }
                }
                return _session;
            }
        }

        StatisticReferrer _referrer;
        public StatisticReferrer ReferrerUrl
        {
            get
            {
                if (_referrer == null)
                {
                    string urlref = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : string.Empty;
                    _referrer = CmsFacade.GetReferrerByUrl(urlref);
                    if (_referrer == null)
                    {
                        _referrer = new StatisticReferrer();
                        _referrer.Url = urlref;
                        _referrer.Save();
                    }
                }
                return _referrer;
            }
        }


        public StatisticsControl()
        {

        }

        protected override void  OnPreRender(EventArgs e)
        {
 	         base.OnPreRender(e);

            if (!Logged)
            {
                StatisticLog statlog = new StatisticLog();
                statlog.Session = VisitorSession;
                statlog.Referrer = ReferrerUrl;
                statlog.DateTime = DateTime.Now;
                if (Manager.PageId != null)
                    statlog.Page = CmsFacade.GetPageById(Manager.PageId.Value);
                statlog.Save();
            }

            Literal literal = new Literal();
            literal.Text = "<!-- Logged with BlazingStats -->";
            Page.Header.Controls.Add(literal);
        }


    }
}
